package persistence.dao;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.StringTokenizer;

import persistence.db.DataSet;
import persistence.db.DatabaseConnector;
import persistence.model.AbstractModel;

public abstract class AbstractDAO {
	private String tableName = "";
	private int id = -1;
	
	private static DatabaseConnector dbConnection = DatabaseConnector.getInstance();

	public String getTableName() {
		return tableName;
	}
	
	public abstract AbstractModel makeModel(ResultSet rset);

	public void setTableName(String tableName) {
		this.tableName = tableName;
	}
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
	public void delete(){
		String query;
		query = "DELETE FROM " + this.tableName + " WHERE ID_" + this.tableName + " = "+ this.getId();
		System.out.println("delete: " + query);
		/* Execute la requete */
		ResultSet result = DatabaseConnector.getInstance().execute(query);
	}
	
	public int getLastId() {
		String query = "SELECT * FROM " + tableName + " WHERE ID_" + this.getTableName() + " = S_PK_" + this.getTableName() + ".currval";
		/* Execute la requete */
		ResultSet result = DatabaseConnector.getInstance().execute(query);
		int res = -1; 
		try {
			res = result.getInt(1);
		} catch (SQLException e) {
			System.out.println("Problème de récupération de l'iendentifiant.\n");
			e.printStackTrace();
		}
		return res;
	}
	
	//Permet de sauver un nouvel enregistrement
	public abstract void save();
	
	//Permet de mettre à jour l'enregistrement d'id id
	public abstract void save(int id);
	
	public abstract DataSet all();
	
	public String dateToString(Date date) {
    	int year;
    	int month;
    	int day;
    	String retour = date.toString();
    	retour = retour.replace('-',' ');
    	StringTokenizer tokenizer = new StringTokenizer(retour);
   	    year = Integer.parseInt(tokenizer.nextToken());
   	    month = Integer.parseInt(tokenizer.nextToken());
   	    day = Integer.parseInt(tokenizer.nextToken());
   	    return day+"/"+month+"/"+year;
	}
}
